<template>
  <div class="login-container">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      auto-complete="on"
      label-position="left"
    >
      <div class="title-container">
        <h3 class="title">乐队管理系统</h3>
      </div>

      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="username"
          v-model="loginForm.username"
          placeholder="用户名或邮箱"
          name="username"
          type="text"
          tabindex="1"
          auto-complete="on"
        />
      </el-form-item>

      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          :key="passwordType"
          ref="password"
          v-model="loginForm.password"
          :type="passwordType"
          placeholder="密码"
          name="password"
          tabindex="2"
          auto-complete="on"
          @keyup.enter.native="handleLogin"
        />
        <span class="show-pwd" @click="showPwd">
          <svg-icon
            :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
          />
        </span>
      </el-form-item>

      <el-form-item>
        <div class="container">
          <el-input
            v-model="inputImgCode"
            placeholder="请输入右侧验证码"
            name="inputImgCode"
            type="text"
            tabindex="1"
            auto-complete="on"
          ></el-input>
          <div class="img-canvas">
            <canvas
              id="canvas"
              :width="width"
              :height="height"
              @click="handleDraw"
            ></canvas>
          </div>
        </div>
      </el-form-item>

      <el-button
        :loading="loginLoading"
        type="primary"
        style="width: 40%; margin-bottom: 30px; margin-left: 5px"
        @click.native.prevent="handleLogin"
        >登录</el-button
      >
      <el-button
        type="primary"
        style="width: 40%; margin-bottom: 30px; margin-left: 65px"
        @click="$router.push('/register')"
        >注册</el-button
      >
      <el-button
        type="primary"
        class="small-button"
        style="
          background: transparent;
          color: white;
          border: none;
          margin-left: 80%;
        "
        @click="$router.push('/forgetPassword')"
      >
        忘记密码？
      </el-button>

    </el-form>
    <!-- 人机验证 -->
  </div>
</template>

<script>
// import Vcode from "vue-puzzle-vcode"; //人机验证
export default {
  name: "Login",
  // components: { Vcode },
  data() {
    const validateUsername = (rule, value, callback) => {
      // if (!validUsername(value)) {
      //   callback(new Error("请输入用户名或邮箱"));
      // } else {
      callback();
      // }
    };
    const validatePassword = (rule, value, callback) => {
      // if (value.length < 6) {
      //   callback(new Error("密码不能少于6位"));
      // } else {
      callback();
      // }
    };
    return {
      // isShow: false, //人机验证的图片是否显示
      loginForm: {
        username: "",
        password: "",
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", validator: validateUsername },
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword },
        ],
      },
      loginLoading: false,
      passwordType: "password",
      redirect: undefined,
      //图片验证码所需
      allTexts: "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890", // 字符串
      width: 120,
      height: 40,
      imgCode: "", //自动生成的
      inputImgCode: "", //用户输入的
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  mounted() {
    // 初始化绘制图片验证码
    this.imgCode = this.draw();
  },
  methods: {
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    //关闭验证
    // 关闭滑块验证后提示用户取消验证
    // onClose() {
    //   this.isShow = false;
    //   this.$message({
    //     message: "取消验证！",
    //     type: "warning",
    //   });
    // },
    //人机验证（登录请求在这里发送）
    //滑块验证成功
    // onSuccess(msg) {
    //   this.isShow = false;
    //   //执行登录
    //   this.loading = true;
    //   this.$store
    //     .dispatch("user/login", this.loginForm)
    //     .then(() => {
    //       console.log("登录成功");
    //       this.$router.push("/");
    //       this.loading = false;
    //     })
    //     .catch(() => {
    //       this.loading = false;
    //     });
    //     this.handleDraw()
    // },

    //点击登录
    handleLogin() {
      //先判断验证码是否为空或正确
      if (this.inputImgCode === "") {
        this.handleDraw();
        this.$message.error("验证码不能为空");
      } else if (
        this.imgCode.toLowerCase() !== this.inputImgCode.toLowerCase()
      ) {
        this.handleDraw();
        this.$message.error("验证码错误，请重新输入");
      } else {
        // this.isShow = true; //显示人机验证
        //执行登录
        this.loginLoading = true;
        this.$store
          .dispatch("user/login", this.loginForm)
          .then(() => {
            console.log("登录成功");
            this.$router.push("/");
            this.loginLoading = false;
          })
          .catch(() => {
            this.loginLoading = false;
          });
        this.handleDraw();
      }
    },
    //图片验证码所需方法
    // 点击图片刷新
    handleDraw() {
      this.imgCode = this.draw();
    },
    // 产生随机数
    randomNum(min, max) {
      return parseInt(Math.random() * (max - min) + min);
    },
    // 产生随机颜色
    randomColor(min, max) {
      const r = this.randomNum(min, max);
      const g = this.randomNum(min, max);
      const b = this.randomNum(min, max);
      return `rgb(${r},${g},${b})`;
    },
    // 绘图
    draw() {
      const canvas = document.getElementById("canvas");
      const ctx = canvas.getContext("2d");
      //!! 1.填充背景颜色，背景颜色要浅一点
      ctx.fillStyle = this.randomColor(180, 230);
      // 填充的位置
      ctx.fillRect(0, 0, this.width, this.height);
      let imgCode = "";
      //!! 2.随机产生字符串，并且随机旋转
      for (let i = 0; i < 4; i++) {
        // 随机的四个字
        const text = this.allTexts[this.randomNum(0, this.allTexts.length)];
        imgCode += text;
        // 随机的字体大小
        const fontSize = this.randomNum(18, 40);
        // 字体随机的旋转角度
        const deg = this.randomNum(-30, 30);
        ctx.font = fontSize + "px Arial";
        ctx.textBaseline = "top";
        ctx.fillStyle = this.randomColor(80, 150);
        ctx.save();
        ctx.translate(30 * i + 15, 15);
        ctx.rotate((deg * Math.PI) / 180);
        ctx.fillText(text, -15 + 5, -15);
        ctx.restore();
      }
      //!! 3.随机产生5条干扰线
      for (let i = 0; i < 5; i++) {
        ctx.beginPath();
        ctx.moveTo(
          this.randomNum(0, this.width),
          this.randomNum(0, this.height)
        );
        ctx.lineTo(
          this.randomNum(0, this.width),
          this.randomNum(0, this.height)
        );
        ctx.strokeStyle = this.randomColor(180, 230);
        ctx.closePath();
        ctx.stroke();
      }
      //!! 4.随机产生40个干扰的小点
      for (let i = 0; i < 40; i++) {
        ctx.beginPath();
        ctx.arc(
          this.randomNum(0, this.width),
          this.randomNum(0, this.height),
          1,
          0,
          2 * Math.PI
        );
        ctx.closePath();
        ctx.fillStyle = this.randomColor(150, 200);
        ctx.fill();
      }
      return imgCode;
    },
  },
};
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;
.container {
  display: flex;
  align-items: center;
}

.img-canvas {
  margin-left: 10px; // 根据需要进行调整，用于控制图片和输入框之间的间距
  height: 39px;
}
.login-container {
  min-height: 100%;
  width: 100%;
  // background-color: $bg;
  background: url(../../assets/register.jpg);
  overflow: hidden;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 60px;
      color: #3193e4;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
